﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace Oxage.Windows.Controls
{
	/// <summary>
	/// Generates a data form from a class.
	/// TODO: Fully implement this UserControl or create a custom control.
	/// </summary>
	public partial class DataForm : UserControl
	{
		#region Constructor
		public DataForm()
		{
			InitializeComponent();
		}
		#endregion

		#region Dependency properties
		public object Model
		{
			get { return (object)GetValue(ModelProperty); }
			set { SetValue(ModelProperty, value); }
		}

		public static readonly DependencyProperty ModelProperty = DependencyProperty.Register("Model", typeof(object), typeof(DataForm), new PropertyMetadata(ModelChanged));

		private static void ModelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var view = d as DataForm;
			var model = e.NewValue;
			if (view != null && model != null)
			{
				view.BuildForm(model);
			}
		}
		#endregion

		#region Protected methods
		protected void BuildForm(object model)
		{
			int row = 0;
			LayoutRoot.Children.Clear();
			LayoutRoot.RowDefinitions.Clear();
			LayoutRoot.DataContext = model;
			var properties = model.GetType().GetProperties();
			foreach (var property in properties)
			{
				var attribute = Attribute.GetCustomAttribute(property, typeof(DataFormAttribute)) as DataFormAttribute;
				if (attribute != null)
				{
					//Create new rows
					if (LayoutRoot.RowDefinitions.Count > 0)
					{
						//Margin
						LayoutRoot.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(5) });
					}
					LayoutRoot.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

					var label = new TextBlock();
					label.TextAlignment = TextAlignment.Right;
					label.Text = attribute.FriendlyName;
					//label.Style = LabelTextStyle
					label.Margin = new Thickness(0, 2, 0, 0);
					Grid.SetColumn(label, 0);
					Grid.SetRow(label, row);
					LayoutRoot.Children.Add(label);

					var input = new TextBox();
					input.SetBinding(TextBox.TextProperty, new Binding(property.Name) { Mode = BindingMode.TwoWay });
					//input.Text = "" + property.GetValue(model, null);
					Grid.SetColumn(input, 2);
					Grid.SetRow(input, row);
					LayoutRoot.Children.Add(input);

					row += 2;
				}
			}
		}
		#endregion
	}
}
